package cn.edu.scau.daoImpl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import cn.edu.scau.dao.BlogDao;
import cn.edu.scau.entity.Blog;

@Repository("blogDaoImpl")
public class BlogDaoImpl extends BaseDaoImpl<Blog> implements BlogDao {

	/**
	 * 分页，按照时间获取博客
	 * 
	 * @param pageNo
	 * 第几页
	 * @param pageSize
	 * 页面展示条数大小
	 */
	public List<Blog> getAllBlogByPage(int pageNo, int pageSize) {

		// hql语句
		String hql = "from " + Blog.class.getSimpleName() + " b order by b.time desc";
		// 查询出Blog
		List<Blog> blogs = this.findByPage(hql, pageNo, pageSize);
		return blogs;
	}


	/**
	 * 搜索出来的博客条数
	 * 
	 * @param condition
	 * 搜索条件
	 */
	public long searchBlogsCount(String condition) {

		List<?> list = findByHql("select count(*) from " + Blog.class.getSimpleName() + " b where b.content like "
				+ "'%" + condition + "%'");
		if (list != null && list.size() == 1) {
			return (Long) list.get(0);
		}
		return 0;
	}

	/**
	 * 搜索博客
	 * 
	 * @param condition
	 * 搜索条件
	 */
	public List<Blog> findBlogsByCondition(String condition, Integer pageNo, Integer pageSize) {

		// hql语句
		String hql = "from " + Blog.class.getSimpleName() + " b where b.content like " + "'%" + condition + "%'"
				+ "  order by b.time desc";
		// 分页查找
		List<Blog> blogs = this.findByPage(hql, pageNo, pageSize);
		return blogs;

	}

	/**
	 * 列出当天点赞榜
	 * 
	 * @param pageNo
	 * 页数
	 */
	@SuppressWarnings("unchecked")
	public List<Blog> findBlogByUpvoteRank(Integer pageNo) {

		Session session = getSessionFactory().openSession();
		Calendar cal = Calendar.getInstance();
		Date date = new Date();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		String begin = new SimpleDateFormat().format(cal.getTime());
		System.out.println(begin);
		cal.add(Calendar.DATE, 1);
		String end = new SimpleDateFormat().format(cal.getTime());
		System.out.println(end);
		String hql = "from " + Blog.class.getSimpleName()
				+ " b where b.time between ?0 and ?1 order by b.upvoteNum desc, b.time desc";
		Object[] objects = new Object[2];
		objects[0] = begin;
		objects[1] = end;
		List<Blog> blogs = this.findByPage(hql, pageNo, 10, objects);
		session.flush();
		session.close();
		return blogs;

	}

}